<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Task\Services\TaskService;
use Encore\Admin\Layout\Content;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    public function index(Content $content,Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {
            $size = $request->input('size',15);
            $title = $request->input('title','');
            //列表查询
            $result = DB::table('task')->where('status','>=',0);
            if ( !empty($title) ) {
                $result = $result->where('title','like','%'.$title.'%');
            }
            $result = $result->paginate($size);
            $content->body(view("task.index",['result'=>$result]));
        });
    }

    /**
     * 获取任务详情
     */
    public function get_task(Request $request){
        $task_id = $request->input('id',0);
        if ( empty($task_id) ) return response()->error("PARAM_EMPTY");
        $taskData = DB::table('task')->where('id',$task_id)->first();
        if ( empty($taskData) ) return response()->error("PARAM_ERROR");
        $taskData = get_object_vars($taskData);
        $target = DB::table('dictionary')->select(['value'])->where('key','target')->first();
        $amplitude = DB::table('dictionary')->select(['value'])->where('key','amplitude')->first();
        $taskData['target'] = empty($target->value) ? 0 : $target->value;
        $taskData['amplitude'] = empty($amplitude->value) ? 0 : $amplitude->value;
        return response()->success($taskData);
    }

    /**
     * 添加任务
     */
    public function add_task(Request $request){
        //数据验证
        $title = $request->input('title','');
//        $claim =$request->input('claim','');
        $coin = $request->input('coin',0);
        $code = $request->input('code','');
        $start_time = $request->input('start_time','');
        $end_time = $request->input('end_time','');
        $remark = $request->input('remark','');
        $image = $request->input('image','');
        $sort = $request->input('sort',0);
        if ( empty($title) || empty($coin) ) return response()->error("PARAM_EMPTY");
        if ( !empty($end_time) && !empty($start_time) && strtotime(date('Y-m-d'.' '.$end_time,time())) <= strtotime(date('Y-m-d'.' '.$start_time,time())) ) return response()->error("PARAM_ERROR");
        //添加任务数据
        $dataAddArr = [
            'title'         => $title,
            'claim'         => '',
            'code'          => $code,
            'coin'          => $coin,
            'start_time'    => $start_time,
            'end_time'      => $end_time,
            'remark'        => $remark,
            'image'         => $image,
            'sort'          => $sort,
        ];
        DB::beginTransaction();
        try{
            $result = TaskService::addTask($dataAddArr);
            if ( empty($result) ) throw new \Exception('ADD_FAILURE');
            //修改默认血糖目标值跟增幅数值的配置数据（只有在控糖达标任务下才会修改这个两个值）
            if ( isset($_POST['code']) && $_POST['code'] == 'SUGAR' ) {
                if ( isset($_POST['target']) ) {
                    $result = DB::table('dictionary')->where('key','target')->update(['value'=>$_POST['target']]);
                    if ( empty($result) && $result !== 0 ) throw new \Exception('ADD_FAILURE');
                }
                if ( isset($_POST['amplitude']) ) {
                    $result = DB::table('dictionary')->where('key','amplitude')->update(['value'=>$_POST['amplitude']]);
                    if ( empty($result) && $result !== 0 ) throw new \Exception('ADD_FAILURE');
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->error("ADD_FAILURE");
        }
        return response()->success();
    }

    /**
     * 修改任务
     */
    public function update_task(Request $request){
        $task_id = $request->input('id',0);
        if ( empty($task_id) ) return response()->error("PARAM_EMPTY");
        $dataUpdateArr = ['id'=>$task_id];
        !isset($_POST['title']) || empty($_POST['title']) ? : $dataUpdateArr['title'] = $request->input('title');
        !isset($_POST['claim']) || empty($_POST['claim']) ? : $dataUpdateArr['claim'] = $request->input('claim');
        !isset($_POST['coin']) || empty($_POST['coin']) ? : $dataUpdateArr['coin'] = $request->input('coin');
        !isset($_POST['start_time']) ? : $dataUpdateArr['start_time'] = $request->input('start_time',0);
        !isset($_POST['code']) ? : $dataUpdateArr['code'] = $request->input('code','');
        !isset($_POST['end_time']) ? : $dataUpdateArr['end_time'] = $request->input('end_time',0);
        !isset($_POST['remark']) ? : $dataUpdateArr['remark'] = $request->input('remark','');
        !isset($_POST['image']) ? : $dataUpdateArr['image'] = $request->input('image','');
        !isset($_POST['sort']) ? : $dataUpdateArr['sort'] = $request->input('sort',0);
        if ( !empty($_POST['code']) && $_POST['code'] != 'HEALTH' ) {
            if ( (isset($_POST['start_time']) && !isset($_POST['end_time'])) || (!isset($_POST['start_time']) && isset($_POST['end_time'])) ) return response()->error("PARAM_ERROR");
            if ( strtotime(date('Y-m-d'.' '.$dataUpdateArr['end_time'],time())) <= strtotime(date('Y-m-d'.' '.$dataUpdateArr['start_time'],time())) ) return response()->error("PARAM_ERROR");
        }
        DB::beginTransaction();
        try{
            $result = TaskService::updateTask($dataUpdateArr);
            if ( empty($result) ) throw new \Exception('UPDATE_FAILURE');
            //修改默认血糖目标值跟增幅数值的配置数据（只有在控糖达标任务下才会修改这个两个值）
            if ( isset($_POST['code']) && $_POST['code'] == 'SUGAR' ) {
                if ( isset($_POST['target']) ) {
                    $result = DB::table('dictionary')->where('key','target')->update(['value'=>$_POST['target']]);
                    if ( empty($result) && $result !== 0 ) throw new \Exception('UPDATE_FAILURE');
                }
                if ( isset($_POST['amplitude']) ) {
                    $result = DB::table('dictionary')->where('key','amplitude')->update(['value'=>$_POST['amplitude']]);
                    if ( empty($result) && $result !== 0 ) throw new \Exception('UPDATE_FAILURE');
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->error("UPDATE_FAILURE");
        }
        return response()->success();
    }

    /**
     * 修改任务状态
     */
    public function delete_task(Request $request){
        $task_id = $request->input('id',0);
        $status = $request->input('status');
        if ( empty($task_id) || !isset($_POST['status']) ) return response()->error("PARAM_EMPTY");
        $dataUpdateArr = ['id'=>$task_id,'status'=>$status];
        $result = TaskService::updateTask($dataUpdateArr);
        if ( empty($result) ) return response()->error("UPDATE_FAILURE");
        return response()->success();
    }
}
